using FtpDownloader.Models;
using FtpDownloader.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace FtpDownloader
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            var logger = host.Services.GetRequiredService<ILogger<Program>>();
            
            try
            {
                logger.LogInformation("FTP下载程序启动...");
                
                // 检查命令行参数
                if (args.Length > 0 && args[0].ToLower() == "--run-once")
                {
                    logger.LogInformation("执行一次性下载任务...");
                    var ftpService = host.Services.GetRequiredService<FtpDownloadService>();
                    await ftpService.DownloadFilesAsync();
                    logger.LogInformation("一次性下载任务完成");
                    return;
                }

                // 程序启动时先执行一次下载任务
                logger.LogInformation("程序启动，执行初始下载任务...");
                var initialFtpService = host.Services.GetRequiredService<FtpDownloadService>();
                await initialFtpService.DownloadFilesAsync();
                logger.LogInformation("初始下载任务完成，开始定时任务服务...");

                // 启动定时任务服务
                await host.RunAsync();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "程序运行时发生错误");
                throw;
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseWindowsService() // 添加Windows服务支持
                .ConfigureAppConfiguration((context, config) =>
                {
                    // 获取程序所在目录，而不是当前工作目录
                    var basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? Directory.GetCurrentDirectory();
                    config.SetBasePath(basePath)
                          .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                          .AddEnvironmentVariables()
                          .AddCommandLine(args);
                })
                .ConfigureServices((context, services) =>
                {
                    // 配置选项
                    services.Configure<FtpSettings>(
                        context.Configuration.GetSection("FtpSettings"));
                    services.Configure<ScheduleSettings>(
                        context.Configuration.GetSection("ScheduleSettings"));

                    // 注册服务
                    services.AddScoped<FtpDownloadService>();
                    services.AddHostedService<ScheduledTaskService>();
                })
                .ConfigureLogging((context, logging) =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                    logging.AddDebug();
                    
                    // 只在Windows平台添加事件日志
                    if (OperatingSystem.IsWindows())
                    {
                        logging.AddEventLog();
                    }
                    
                    // 添加文件日志
                    logging.AddFile("logs/ftp-downloader-{Date}.log", 
                        minimumLevel: LogLevel.Information);
                });
    }
}
